<template>
  <div class="profile-register">
    <div class="profile-container">
      <!-- 头部信息 -->
      <div class="header-section">
        <div class="avatar-section">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            :on-change="handleAvatarUpload"
          >
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar">
            <div v-else class="avatar-placeholder">
              <i class="el-icon-plus"></i>
              <div class="avatar-text">添加头像</div>
            </div>
          </el-upload>
        </div>
        <div class="title-section">
          <h2 class="profile-title">创建我的婚恋档案</h2>
          <p class="profile-subtitle">完善个人信息，开始寻找生命中的TA！本网站保证绝对不泄露用户的隐私！</p>
        </div>
      </div>

      <el-form
        ref="profileForm"
        :model="profileForm"
        :rules="profileRules"
        class="profile-form"
        label-width="80px"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <i class="el-icon-user"></i>
            基本信息
          </h3>

          <el-form-item label="昵称" prop="nickName">
            <el-input
              v-model="profileForm.nickName"
              placeholder="请输入昵称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model="profileForm.realName"
              placeholder="请输入真实姓名（可选）"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profileForm.gender" class="gender-group">
              <el-radio label="0" class="gender-radio">
                <i class="el-icon-male"></i>
                男
              </el-radio>
              <el-radio label="1" class="gender-radio">
                <i class="el-icon-female"></i>
                女
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <div class="form-row">
            <el-form-item label="出生日期" prop="birthDate" class="form-item-half">
              <el-date-picker
                v-model="profileForm.birthDate"
                align="right"
                type="date"
                placeholder="选择日期"
                >
              </el-date-picker>
<!--              <el-select v-model="profileForm.birthDate" placeholder="请选择" style="width: 100%">-->
<!--                <el-option-->
<!--                  v-for="year in birthYearOptions"-->
<!--                  :key="year"-->
<!--                  :label="year + '年'"-->
<!--                  :value="year"-->
<!--                />-->
<!--              </el-select>-->
            </el-form-item>
            <el-form-item label="身高" prop="height" class="form-item-half">
              <el-input
                v-model="profileForm.height"
                placeholder="身高"
                maxlength="3"
              >
                <template slot="append">cm</template>
              </el-input>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="体重" prop="weight" class="form-item-half">
              <el-input
                v-model="profileForm.weight"
                placeholder="体重"
                maxlength="3"
              >
                <template slot="append">kg</template>
              </el-input>
            </el-form-item>
            <el-form-item label="婚恋状态" prop="maritalStatus" class="form-item-half">
              <el-select v-model="profileForm.maritalStatus" placeholder="请选择" style="width: 100%">
                <el-option label="未婚" value="未婚" />
                <el-option label="离异" value="离异" />
                <el-option label="丧偶" value="丧偶" />
              </el-select>
            </el-form-item>
          </div>

          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="profileForm.phone"
              placeholder="请输入手机号码"
              maxlength="11"
              type="tel"
            />
          </el-form-item>

          <el-form-item label="所在地区" prop="regionIds">
            <region-select
              v-model="profileForm.regionIds"
              mode="cascader"
              :level="3"
              placeholder="请选择省/市/区"
              @change="handleRegionChange"
            />
          </el-form-item>
        </div>

        <!-- 学历职业 -->
        <div class="form-section">
          <h3 class="section-title">
            <i class="el-icon-office-building"></i>
            学历职业
          </h3>

          <div class="form-row">
            <el-form-item label="学历" prop="education" class="form-item-half">
              <el-select v-model="profileForm.education" placeholder="请选择学历">
                <el-option label="初中" value="初中" />
                <el-option label="高中" value="高中" />
                <el-option label="大专" value="大专" />
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
              </el-select>
            </el-form-item>
            <el-form-item label="年收入" prop="annualIncome" class="form-item-half">
              <el-input
                v-model="profileForm.annualIncome"
                placeholder="请输入年收入（粗略）"
                maxlength="30"
              />
            </el-form-item>
          </div>

          <el-form-item label="职业" prop="position">
            <el-input
              v-model="profileForm.position"
              placeholder="请输入职业"
              maxlength="30"
            />
          </el-form-item>
        </div>

        <!-- 个人描述 -->
        <div class="form-section">
          <h3 class="section-title">
            <i class="el-icon-chat-dot-round"></i>
            个人描述
          </h3>

          <el-form-item label="自我介绍" prop="selfIntroduction">
            <el-input
              v-model="profileForm.selfIntroduction"
              type="textarea"
              :rows="4"
              placeholder="简单介绍一下自己，包括性格特点、兴趣爱好等（最多200字）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="择偶要求" prop="mateRequirement">
            <el-input
              v-model="profileForm.mateRequirement"
              type="textarea"
              :rows="3"
              placeholder="描述您对另一半的期望和要求（最多150字）"
              maxlength="150"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button
            type="primary"
            size="large"
            :loading="submitLoading"
            @click="handleSubmit"
            class="submit-btn"
          >
            {{ submitLoading ? '提交中...' : '创建我的档案' }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { createProfile, checkPhoneExists, uploadAvatar } from '@/api/dating/profile'
import RegionSelect from '@/components/RegionSelect'

export default {
  name: 'ProfileRegister',
  components: {
    RegionSelect
  },
  data() {
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        // 检查手机号是否已存在
        checkPhoneExists(value).then(response => {
          if (!response.data) {
            callback(new Error('该手机号已被注册'))
          } else {
            callback()
          }
        }).catch(() => {
          callback()
        })
      }
    }

    // 身高验证
    const validateHeight = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入身高'))
      } else if (isNaN(value) || value < 140 || value > 220) {
        callback(new Error('请输入合理的身高范围(140-220cm)'))
      } else {
        callback()
      }
    }

    // 体重验证
    const validateWeight = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入体重'))
      } else if (isNaN(value) || value < 35 || value > 200) {
        callback(new Error('请输入合理的体重范围(35-200kg)'))
      } else {
        callback()
      }
    }

    return {
      submitLoading: false,
      profileForm: {
        nickName: '',
        realName: '',
        gender: '',
        birthYear: '',
        height: '',
        weight: '',
        phone: '',
        city: '',
        regionIds: [],
        education: '',
        position: '',
        annualIncome: '',
        maritalStatus: '',
        selfIntroduction: '',
        mateRequirement: '',
        avatar: ''
      },
      profileRules: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur' }
        ],
        realName: [
          { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        birthYear: [
          { required: true, message: '请选择出生年份', trigger: 'change' }
        ],
        height: [
          { required: true, validator: validateHeight, trigger: 'blur' }
        ],
        weight: [
          { required: true, validator: validateWeight, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请输入所在城市', trigger: 'blur' }
        ],
        education: [
          { required: true, message: '请选择学历', trigger: 'change' }
        ],
        position: [
          { required: true, message: '请输入职业', trigger: 'blur' }
        ],
        annualIncome: [
          { required: true, message: '请选择年收入', trigger: 'change' }
        ],
        maritalStatus: [
          { required: true, message: '请选择婚恋状态', trigger: 'change' }
        ],
        selfIntroduction: [
          { required: true, message: '请输入自我介绍', trigger: 'blur' },
          { min: 10, max: 200, message: '自我介绍长度在10到200个字符', trigger: 'blur' }
        ],
        mateRequirement: [
          { required: true, message: '请输入择偶要求', trigger: 'blur' },
          { min: 10, max: 150, message: '择偶要求长度在10到150个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 生成出生年份选项（当前年份-60 到 当前年份-18）
    birthYearOptions() {
      const currentYear = new Date().getFullYear()
      const options = []
      for (let year = currentYear - 18; year >= currentYear - 60; year--) {
        options.push(year)
      }
      return options
    }
  },
  methods: {
    // 头像文件变化时处理
    handleAvatarUpload(file) {
      if (this.beforeAvatarUpload(file.raw)) {
        // 使用头像上传API
        uploadAvatar(file.raw).then(response => {
          this.profileForm.avatar = response.data.url
          this.$message.success('头像上传成功')
        }).catch(() => {
          this.$message.error('头像上传失败')
          // 临时显示本地预览
          this.profileForm.avatar = URL.createObjectURL(file.raw)
        })
      }
    },

    // 头像上传成功回调（保留用于兼容）
    handleAvatarSuccess(res, file) {
      // 这个方法现在由 handleAvatarUpload 处理
    },

    // 头像上传前验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 提交表单
    handleSubmit() {
      this.$refs.profileForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          // 构建提交数据
          const submitData = {
            ...this.profileForm,
            // 根据出生年份计算年龄
            age: new Date().getFullYear() - this.profileForm.birthYear,
            // 设置默认值
            memberStatus: '1', // 正常状态
            vipLevel: 0, // 普通会员
            // 生成人员编号（可以根据实际需求调整）
            memberNo: 'M' + Date.now()
          }

          createProfile(submitData).then(response => {
            this.$modal.msgSuccess('个人档案创建成功！')
            this.handleReset()
            // 跳转到登录页面或其他页面
            this.$router.push('/login')
          }).catch(() => {
            this.$modal.msgError('创建失败，请稍后重试')
          }).finally(() => {
            this.submitLoading = false
          })
        } else {
          this.$message.error('请完善必填信息')
          return false
        }
      })
    },

    // 重置表单
    handleReset() {
      this.$refs.profileForm.resetFields()
      this.profileForm.avatar = ''
    },
    // 地区选择变化处理
    handleRegionChange(regionIds) {
      this.profileForm.regionIds = regionIds;
      // 同时更新province、city、district字段，保持兼容性
      if (regionIds && regionIds.length > 0) {
        // 这里需要根据regionIds获取地区名称
        // 可以通过调用API获取，或者从组件中获取
        this.getRegionNames(regionIds);
      } else {
        this.profileForm.province = null;
        this.profileForm.city = null;
        this.profileForm.district = null;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.profile-register {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
  padding: 0;
  overflow-x: hidden;
}

.profile-container {
  background: white;
  max-width: 100%;
  width: 100%;
  min-height: 100vh;
  border-radius: 0;
  padding: 20px 15px;
  box-shadow: none;
  margin: 0;
}

// 头部区域
.header-section {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding: 15px 0;

  .avatar-section {
    margin-right: 15px;
    flex-shrink: 0;
  }

  .title-section {
    flex: 1;
  }
}

.profile-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  line-height: 1.2;
}

.profile-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
  line-height: 1.3;
}

// 头像上传优化
.avatar-uploader {
  .avatar {
    width: 70px;
    height: 70px;
    display: block;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .avatar-placeholder {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    background: linear-gradient(135deg, #ff9a9e, #fecfef);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    border: 3px solid #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    i {
      font-size: 20px;
      color: #fff;
      margin-bottom: 2px;
    }

    .avatar-text {
      font-size: 10px;
      color: #fff;
      font-weight: 500;
    }

    &:hover {
      transform: scale(1.05);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }
}

// 表单样式
.profile-form {
  .form-section {
    margin-bottom: 25px;
    background: #fafafa;
    border-radius: 12px;
    padding: 15px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 15px;
      padding-bottom: 8px;
      border-bottom: 2px solid #e8e8e8;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #ff6b9d;
        font-size: 18px;
      }
    }
  }

  // 表单项间距优化
  .el-form-item {
    margin-bottom: 15px;

    .el-form-item__label {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
      padding-bottom: 5px;
    }

    .el-input__inner,
    .el-textarea__inner {
      border-radius: 8px;
      border: 1px solid #e0e0e0;
      font-size: 14px;

      &:focus {
        border-color: #ff6b9d;
        box-shadow: 0 0 0 2px rgba(255, 107, 157, 0.1);
      }
    }

    .el-select {
      width: 100%;
    }
  }
}

// 性别选择美化
.gender-group {
  width: 100%;

  .gender-radio {
    flex: 1;
    margin-right: 20px;
    border: 1px solid #e0e0e0;
    border-radius: 25px;
    padding: 8px 15px;
    background: #fff;
    transition: all 0.3s;

    &:last-child {
      margin-right: 0;
    }

    i {
      margin-right: 5px;
    }

    &.is-checked {
      border-color: #ff6b9d;
      background: rgba(255, 107, 157, 0.1);
      color: #ff6b9d;
    }
  }
}

// 双列布局
.form-row {
  display: flex;
  gap: 10px;

  .form-item-half {
    flex: 1;
    margin-bottom: 15px;
  }
}

// 提交按钮
.form-actions {
  text-align: center;
  margin-top: 30px;
  padding: 20px 0;

  .submit-btn {
    width: 100%;
    height: 50px;
    font-size: 16px;
    font-weight: 600;
    border-radius: 25px;
    background: linear-gradient(135deg, #ff6b9d, #ff8fab);
    border: none;
    color: white;
    box-shadow: 0 4px 15px rgba(255, 107, 157, 0.3);

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(255, 107, 157, 0.4);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

// 移动端专用样式优化
@media (max-width: 768px) {
  .profile-register {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  }

  .profile-container {
    padding: 15px 12px;
    min-height: 100vh;
  }

  .header-section {
    margin-bottom: 20px;
    padding: 10px 0;
  }

  .profile-title {
    font-size: 20px;
  }

  .profile-subtitle {
    font-size: 13px;
  }

  .profile-form {
    .form-section {
      margin-bottom: 20px;
      padding: 12px;

      .section-title {
        font-size: 15px;
        margin-bottom: 12px;

        i {
          font-size: 16px;
        }
      }
    }

    .el-form-item {
      margin-bottom: 12px;

      .el-form-item__label {
        font-size: 13px;
        padding-bottom: 3px;
      }

      .el-input__inner,
      .el-textarea__inner {
        font-size: 14px;
        padding: 10px 12px;
      }
    }
  }

  .form-row {
    gap: 8px;

    .form-item-half {
      margin-bottom: 12px;
    }
  }

  .gender-group {
    .gender-radio {
      margin-right: 15px;
      padding: 6px 12px;
      font-size: 14px;
    }
  }

  .form-actions {
    margin-top: 25px;
    padding: 15px 0;

    .submit-btn {
      height: 48px;
      font-size: 15px;
    }
  }
}

// 超小屏幕优化
@media (max-width: 480px) {
  .profile-container {
    padding: 12px 10px;
  }

  .header-section {
    .avatar-section {
      margin-right: 12px;
    }
  }

  .avatar-uploader {
    .avatar,
    .avatar-placeholder {
      width: 60px;
      height: 60px;
    }

    .avatar-placeholder {
      i {
        font-size: 18px;
      }

      .avatar-text {
        font-size: 9px;
      }
    }
  }

  .profile-title {
    font-size: 18px;
  }

  .profile-subtitle {
    font-size: 12px;
  }

  .form-row {
    flex-direction: column;
    gap: 0;
  }

  .gender-group {
    .gender-radio {
      margin-right: 10px;
      font-size: 13px;
    }
  }
}

// 输入框获焦效果
.el-input.is-focus .el-input__inner,
.el-textarea.is-focus .el-textarea__inner {
  border-color: #ff6b9d !important;
  box-shadow: 0 0 0 2px rgba(255, 107, 157, 0.1) !important;
}

// 选择器下拉样式
.el-select-dropdown__item.selected {
  color: #ff6b9d;
  font-weight: 600;
}

.el-select-dropdown__item:hover {
  background-color: rgba(255, 107, 157, 0.1);
}
</style>
